package com.duke.shaking;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.duke.shaking.auth.LoginActivity;
import com.duke.shaking.net.AsyncHttpResponseWithResultHandler;
import com.duke.shaking.net.NetUtils;
import com.duke.shaking.pojo.User;
import com.duke.shaking.profile.InputBirthdayActivity;
import com.duke.shaking.profile.InputNicknameActivity;
import com.duke.shaking.utils.PrefUtils;

import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class StartupActivity extends BaseActivity {

	private String telNo;
	private String password;
	private boolean autoLogin;
	private Thread loadingTread;
	private Class<?> theNextActivity;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_startup);
        checkUserState();
        
    }
	
	protected void onPause() {
		/*if (loadingTread != null) {
			loadingTread.stop();
			loadingTread = null;
		}*/
		super.onPause();
	}
	
	private void startLoadingThread() {
		loadingTread = new Thread() {
            @Override
            public void run() {
            	try {
            		sleep(1 * 1000);
            	}
            	catch (InterruptedException e) {
            		
            	}
                finally {
                    finish();
                    info("to main activity");
                    if (theNextActivity != null) {
                    	go(theNextActivity, null, null);
                    }
                    //stop();
                }
            }
        };
        loadingTread.start();
	}
	
	private void checkUserState() {
		PrefUtils prefUtils = PrefUtils.getInstance(this, this.getString(R.string.registerPref));
		telNo = prefUtils.getString(this.getString(R.string.savedTelNo), null);
		password = prefUtils.getString(this.getString(R.string.savedPassword), null);
		autoLogin = prefUtils.getBoolean(this.getString(R.string.bAutoLogin), false);
		
		if (telNo != null && !telNo.equals("")
			&& password != null && !password.equals("")
			&& autoLogin) {
			login();
		}
		else if (telNo != null) {
			theNextActivity = LoginActivity.class;
			startLoadingThread();
		}
		else {
			theNextActivity = MainActivity.class;
			startLoadingThread();
		}
	}
	
	private User assembleUser(JSONObject jsonObj) {
		return LoginActivity.assembleUser(jsonObj);
	}
	
	private void login() {
		AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){

			@Override
			public void onResultSuccess(String response) {
				// TODO Auto-generated method stub
				super.onResultSuccess(response);
				JSONObject jsonObj = this.getBody(response);
				LoginActivity.setLastVersionInfo(jsonObj);
				User user = assembleUser(jsonObj);
				if(user != null) {
					user.setTelNo(telNo);
					user.setPassword(password);
					setMe(user);
					
					Class<?> cls = LoginActivity.getNextActivityByUserStatus(user);
					if (cls != null) {
						ShakeApplication.getShared().afterLogin(user);
						finish();
						go(cls);
					}

				} else {
					finish();
					go(LoginActivity.class);
				}
			}

			@Override
			public void onResultFailure(String result) {
				// TODO Auto-generated method stub
				super.onResultFailure(result);
				finish();
				go(LoginActivity.class);
			}
			
			@Override
			public void onFailure(Throwable arg0, String arg1) {
				super.onFailure(arg0, arg1);
				toast(R.string.err_network_issues);
				finish();
				go(LoginActivity.class);
			}
        };
        
        Map<String, String> params = new HashMap<String, String>();
        params.put(NetUtils.MOBILE, telNo);
        params.put(NetUtils.PASSWORD, password);
        NetUtils.login(this, responseHandler, params);
	}
}
